package mapper

import (
	"context"
	"github.com/sirupsen/logrus"
	"go-blockchain-from-scratch/config"
	"go-blockchain-from-scratch/constants"
)

//go 1.8 之后注释掉
type any = interface{}

func InsertOne(database string, collection string, data any) bool {
	collect := config.MgoClient.Database(database).Collection(collection)
	timeoutCtx, cancel := context.WithTimeout(context.TODO(), constants.TimeOut)
	defer cancel()
	_, err := collect.InsertOne(timeoutCtx, data)
	if err != nil {
		return false
	}

	return true
}

func Select(database string, collection string, filter any, data any) {
	collect := config.MgoClient.Database(database).Collection(collection)
	timeoutCtx, cancel := context.WithTimeout(context.TODO(), constants.TimeOut)
	defer cancel()
	cursor, err := collect.Find(timeoutCtx, filter)
	if err != nil {
		logrus.Error(err)
		return
	}
	if err = cursor.All(context.TODO(), data); err != nil {
		logrus.Error(err)
	}
	return
}

func SelectOne(database string, collection string, filter any, data any) error {
	collect := config.MgoClient.Database(database).Collection(collection)
	timeoutCtx, cancel := context.WithTimeout(context.TODO(), constants.TimeOut)
	defer cancel()
	err := collect.FindOne(timeoutCtx, filter).Decode(data)
	if err != nil {
		return err
	}
	logrus.Info(data)
	return nil
}

func Update(database string, collection string, filter any, data any) {
	collect := config.MgoClient.Database(database).Collection(collection)
	timeoutCtx, cancel := context.WithTimeout(context.TODO(), constants.TimeOut)
	defer cancel()
	_, err := collect.UpdateOne(timeoutCtx, filter, data)
	if err != nil {
		logrus.Error(err)
	}
	logrus.Info(data)
	return

}
